package org.tang.springcloudvv.mybatis;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.config.JDBCConnectionConfiguration;
import org.mybatis.generator.config.TableConfiguration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/*
 * tangfuzhong
 * 根据多个配置文件生成myBatis代码
 */
public class MybatisGeneratorTool {

	static List<String> listFiles = new ArrayList<String>();
	static
	{		
		listFiles.add("gen-1-user.xml");
	}
	
	// MBG执行过程中的警告信息
	private static List<String> warnings = new ArrayList<String>();
	private static List<String> warnings_check = new ArrayList<String>();
	private static List<String> listTableName = new ArrayList<String>();//所有
	private static List<String> listTableNameRepeat = new ArrayList<String>();//重复的表对象配置
	
	
	protected static void build()
	{
		System.out.println("begin");
		
		for (String fileName : listFiles) {
			build(warnings,warnings_check, fileName);
		}

		for (String warning : warnings) {
			System.out.println(warning);
		}
		for (String warning : warnings_check) {
			System.out.println(warning);
		}

		if (dataBaseName.equals(db_product))
		{
			System.out.println("context: " + dataBaseName+" , 生产");
		}
		else
		{
			System.out.println("context: " + dataBaseName+" , 开发&测试");
		}
	}

	private static void build(List<String> warnings,List<String> warnings_check, String fileName) {

		try {
			boolean overwrite = true;// 当生成的代码重复时，覆盖源代码
			InputStream is = new FileInputStream(new File(getXmlFilePath()+fileName));

			ConfigurationParser cp = new ConfigurationParser(warnings);
			DefaultShellCallback shellCallback = new DefaultShellCallback(overwrite);
			Configuration configuration = null;
			configuration = cp.parseConfiguration(is);
			is.close();
			
			resetConnectionUrl(configuration);

			resetPath(configuration);

			checkTable(configuration);
			
			int hasTableCount = hasTableCount(configuration);
			warnings_check.add("表对象要生成数量："+hasTableCount+", "+fileName);
			if (hasTableCount == 0)
			{
				//没有则不执行			
			}
			else
			{
				MyBatisGenerator myBatisGenerator = new MyBatisGenerator(configuration, shellCallback, warnings);
				myBatisGenerator.generate(null);	
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	private static void resetPath(Configuration configuration)
	{
		List<Context> listContext = configuration.getContexts();
		for (Context context:listContext) {
			String targetObject = context.getJavaClientGeneratorConfiguration().getTargetProject();
			context.getJavaClientGeneratorConfiguration().setTargetProject(getTargetPath(targetObject));

			String targetObjecJavatModel = context.getJavaModelGeneratorConfiguration().getTargetProject();
			context.getJavaModelGeneratorConfiguration().setTargetProject(getTargetPath(targetObjecJavatModel));

			String targetObjecMapper = context.getSqlMapGeneratorConfiguration().getTargetProject();
			context.getSqlMapGeneratorConfiguration().setTargetProject(getTargetPath(targetObjecMapper));
		}
	}
	//gen.properties配置的相对路径，转换成绝对路径
	private static String getTargetPath(String path)
	{
		if (path.startsWith("src/"))
		{
			String currentPath = Class.class.getClass().getResource("/").getPath();
			currentPath = currentPath.replace("classes/","");
			currentPath = currentPath.replace("target/","");
			path = currentPath+path;
		}
		return path;
	}

	private static void resetConnectionUrl(Configuration configuration) {
		JDBCConnectionConfiguration jDBCConnectionConfiguration = configuration.getContexts().get(0).getJdbcConnectionConfiguration();

		String jdbcUrl_ = jDBCConnectionConfiguration.getConnectionURL();
		jdbcUrl_ = jdbcUrl_+getDataBaseName();
		jDBCConnectionConfiguration.setConnectionURL(jdbcUrl_);
		jdbcUrl  = jDBCConnectionConfiguration.getConnectionURL();
	}

	/*
	 * 如果表只有一个,且为temp_则不必继续执行
	 */
	private static int hasTableCount(Configuration configuration) {
		List<TableConfiguration> list = configuration.getContexts().get(0).getTableConfigurations();
		if (list.size()==1)
		{
			TableConfiguration tableConfiguration = list.get(0);
			if (tableConfiguration.getTableName().equals(TEMP_))
			{
				return 0;
			}
		}
		return list.size()-1;
	}
	
	private static void checkTable(Configuration configuration) {
		List<TableConfiguration> list = configuration.getContexts().get(0).getTableConfigurations();
		for (TableConfiguration tableConfiguration : list) {
			if (tableConfiguration.getTableName().equals(TEMP_))
			{
				continue;
			}
			
			if (listTableName.contains(tableConfiguration.getTableName()))
			{
				listTableNameRepeat.add("重复配置:"+tableConfiguration.getTableName());
			}
			else
			{
				listTableName.add(tableConfiguration.getTableName());
			}
		}
	}

	private static String getXmlFilePath()
	{
		File file = new File("");
		String path = file.getAbsolutePath();
		if (!path.contains(projectName))
		{
			path = xmlFilePath;
		}
		path = path+path_resource;
		return path;
	}

	

	public static String getDataBaseName() {
		return dataBaseName;
	}

	public static void setDataBaseName(String dataBaseName) {
		MybatisGeneratorTool.dataBaseName = dataBaseName;
	}



	private static String  path_resource = "/src/main/resources/gen-conf/";
	private static String  TEMP_ = "temp_";
	public static final String  db_dev_test = "springcloudvv";//开发环境的开发库
	public static final String  db_product = "springcloudvv";//开发环境的生产库快照
	private static String  dataBaseName = null;//从db_dev,db_product选择一个
	private static String jdbcUrl = null;
	private static String projectName = "springcloudvv-mybatis";
	//idea获取路径真是有问题
	private static String xmlFilePath = "/Users/fuzhongtang/IdeaProjects/spring/springcloudvv/springcloudvv-mybatis2/";
	
}
